/* Copyright (c) 2008, Katharine Berry
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Katharine Berry nor the names of any contributors
 *       may be used to endorse or promote products derived from this software
 *       without specific prior written permission.
 *     * This software must not be used to control nuclear weapons.
 *
 * THIS SOFTWARE IS PROVIDED BY KATHARINE BERRY ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL KATHARINE BERRY BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
 
// This is used to handle permission requests (ScriptPermissionRequest)
// and script dialogs (ScriptDialog). There is actually little relation
// between the two at a technical level, but it makes more sense like
// this at the user level. I am a user, therefore it'll be like this.

AjaxLife.ScriptDialogCount = 0;

AjaxLife.ScriptDialogs = function() {

	// For permission requests generated by llRequestPermissions
	function permissionrequest(data)
	{
		var p = AjaxLife.Constants.MainAvatar.ScriptPermission;
		var permissions = "";
		// Check the appropriate permissions and add to the list if needed.
		if(data.Permissions & p.Debit) permissions += _('Permissions.Debit',{})+'\n';
		if(data.Permissions & p.TakeControls) permissions += _('Permissions.TakeControls',{})+'\n';
		if(data.Permissions & p.TriggerAnimation) permissions += _('Permissions.Animate',{})+'\n';
		if(data.Permissions & p.Attach) permissions += _('Permissions.Attach',{})+'\n';
		if(data.Permissions & p.ChangeLinks) permissions += _('Permissions.ChangeLinks',{})+'\n';
		if(data.Permissions & p.TrackCamera) permissions += _('Permissions.TrackCamera',{})+'\n';
		if(data.Permissions & p.ControlCamera) permissions += _('Permissions.ControlCamera',{})+'\n';
		// Ask the question.
		AjaxLife.Widgets.Modal.confirm(
			_('ScriptDialogs.PermissionRequestTitle',{}),
			_('ScriptDialogs.PermissionRequestBody',{
				object: data.ObjectName,
				owner: data.ObjectOwner,
				permission: permissions
			}),
			function(btn) {
				// When we get a response, check what it was. If yes, grant the permissions.
				// If no, grant 0 permissions (i.e. none).
				var respperms = 0;
				if(btn == 'yes')
				{
					respperms = data.Permissions;
				}
				// Send the permission response to the server.
				AjaxLife.Network.Send('ScriptPermissionResponse', {
					ItemID: data.ItemID,
					TaskID: data.TaskID,
					Permissions: respperms
				});
			}
		);
	}
	
	function llDialog(data, buttons, handler){
		++AjaxLife.ScriptDialogCount;
		function btnhandler(index, name) {
			handler(index, name);
			dlg.hide();
		}
		
		// Create a window with a unique ID.
		var dlg = new Ext.BasicDialog('dlg_lldialog_'+ AjaxLife.ScriptDialogCount, {	
			width: '400px',
			height: '300px',
			modal: false,
			shadow: true,
			autoCreate: true,
			title: _("ScriptDialogs.DialogTitle"),
			proxyDrag: !AjaxLife.Fancy,
			closeClick : function(){
				btnhandler(-1,"Ignore");
			}
		});
		
		// Build some content for it.
		var bodyEl = dlg.body.createChild({
			html:'<span></span><br />'
		});
		
		var msgEl = bodyEl.dom.firstChild;
		
		// Make the thing die when you destroy it.
		dlg.on("hide", function() {
			dlg.destroy(true);
		});
		
		dlg.addKeyListener(27, function() {
			dlg.hide();
		});
		
		// Make a button table and style it appropriately.
		var table = $(document.createElement('table'));
		table.addClassName('llDialog');
		var tr = false;
		
		var mkfunction = function(i, btn) {
			return function() {
				btnhandler(i, btn);
			}
		}
		
		// Loop through our buttons, adding them to the table.
		// Every third button we add a new table row, resulting in a grid
		// of buttons with rows of three.
		for(var i = 0; i < buttons.length; ++i)
		{
			var btn = buttons[i];
			if(i % 3 == 0)
			{
				tr = document.createElement('tr');
				table.appendChild(tr);
			}
			var td = document.createElement('td');
			tr.appendChild(td);
			var f = mkfunction(i, btn);
			new Ext.Button(td, {
				text: btn,
				handler: f
			});
		}
		// Place an "Ignore" button at the bottom right.
		dlg.addButton("Ignore",function() {
			btnhandler(-1,"Ignore");
		});
		dlg.body.setStyle({
			background: '#CFE0F5',
			border: '0 none',
			fontSize: '13px'
		});
		// Put the window together and show it.
		var text = _("ScriptDialogs.DialogMessage", {
			object: data.ObjectName,
			first:  data.FirstName,
			last: data.LastName,
			message: data.Message
		});
		msgEl.innerHTML = text || '&#160;';
		msgEl.appendChild(table);
		dlg.show();
		return dlg;
	}
	
	function scriptdialog(data)
	{
		var buttonobj = {};
		data.Buttons.each(function(item) {
			buttonobj[item] = item;
		});
		llDialog(data,data.Buttons,function(index, btn) {
			// If the index isn't -1 (i.e. "Ignore") or the button blank, send back
			// the response.
			if(index == -1 || btn == '') return;
			AjaxLife.Network.Send('ScriptDialogReply', {
				ButtonIndex: index,
				ButtonLabel: btn,
				ChatChannel: data.ChatChannel,
				ObjectID: data.ObjectID
			});
		});
	}

	return {
		init: function() {
			// Register for the events that are triggered by llDialog and llRequestPermissions.
			AjaxLife.Network.MessageQueue.RegisterCallback('ScriptPermissionRequest',permissionrequest);
			AjaxLife.Network.MessageQueue.RegisterCallback('ScriptDialog',scriptdialog);
		}
	};
}();